﻿using shop.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommonTools;

namespace shop.Bll.BasicInfo
{
    public class LogiInfoBll : IPageBll<LogiInfo>
    {
        public string Title => "快递账户";

        public bool EnableEditOnList => true;

        public bool EnableCreateOnList => true;

        public bool RefreshOnOpen => true;

        public Func<object> GetPanelObject { get; set; }

        public Action<int> TurnPage { set; get; }
        public LogiInfo CopyItem(LogiInfo item)
        {
            if (item == null)
                return null;

            var newItem = item.Clone();
            newItem.id = 0;
            newItem.isdel = false;

            return newItem;
        }

        public LogiInfo CreateItem()
        {
            return new LogiInfo() { isdel = false, FTime = DateTime.Now, };
        }

        public async Task<Result> DeleteItem(int id)
        {
            await DB.FSql.Update<LogiInfo>()
                .Where(a => a.id == id && a.isdel == false)
                .Set(a => a.isdel, true)
                .ExecuteAffrowsAsync();

            //await DB.FSql.Insert(new CLogs()
            //{
            //    DocName = nameof(LogiInfo),
            //    Computer = UserBll.CurrentUser.ComputerInfo,
            //    Zdr = UserBll.CurrentUser.Name,
            //    DocId = id.ToString(),
            //    DocAction = "删除",
            //})
            //    .ExecuteAffrowsAsync();

            return new Result(true);
        }


        public async Task<Result<int>> EditCell(string dataPropertyName, object value, LogiInfo data)
        {
            if (data.id == 0)
            {
                data.FTime = await DB.FSql.GetTimeAsync();
                data.isdel = false;

                var nid = await DB.FSql.Insert(data)
                    .ExecuteIdentityAsync();

                data.id = (int)nid;
            }

            var dict = new Dictionary<string, object> { [dataPropertyName] = value };

            // 防止重复
            if (dataPropertyName == nameof(data.logistics_name))
            {
                var rep = await DB.FSql.Select<LogiInfo>()
                    .Where(a => a.isdel == false && a.id != data.id && a.logistics_name == value.ToString())
                    .AnyAsync();
                if (rep)
                {
                    return new Result<int>(false, "名称不能重复");
                }
            }

            var dbRes = await DB.FSql.Update<LogiInfo>()
                .Where(a => a.id == data.id && a.isdel == false)
                .SetDto(dict)
                .ExecuteAffrowsAsync();

            return new Result<int>(true, "!", data.id);
        }

        public IEnumerable<DeclareColumn> GetColumns()
        {
            return new[]
            {
                new DeclareColumn(nameof(LogiInfo.id),"id"){ Visible= false},
                new DeclareColumn(nameof(LogiInfo.LogiAcct),"快递老板"){ Width=150},
                new DeclareColumn(nameof(LogiInfo.logistics_name),"物流公司名称"){ Width=250 },
                new DeclareColumn(nameof(LogiInfo.logistics_no),"物流编号"){ Width=160 },
                new DeclareColumn(nameof(LogiInfo.LogiCompany),"公司"){ Width=120 },
                new DeclareColumn(nameof(LogiInfo.IsAgent),"是否代发"){ Width=80},
                new DeclareColumn(nameof(LogiInfo.FTime),"登记时间"){ ReadOnly= true},
            };
        }

        public async Task<LogiInfo> GetItem(int id)
        {
            return await DB.FSql.Select<LogiInfo>()
                .Where(a => a.isdel == false && a.id == id)
                .ToOneAsync();
        }


        #region 查询参数

        private string _logiAcct;
        private string _logistics_name;
        private string _logiCompany;

        public event Action<object> OnFormShown;
        public event Action<object> OnFormClosed;
        public event Func<PageGridCellEditArg, Task> BeginEditCellAsync;

        #endregion

        /// <summary> 查询ui </summary>
        public virtual ControlBuilder GetUIBuilder()
        {
            return new ControlBuilder()
                .Add<string>(ControlEnum.guanTextBox, "快递老板", c => _logiAcct = c)
                .Add<string>(ControlEnum.guanTextBox, "物流公司名称", c => _logistics_name = c)
                .Add<string>(ControlEnum.guanTextBox, "是否代发", c => _logiCompany = c)
                .AddQueryButton("查询");
        }

        /// <summary> 查询 </summary>
        public async Task<PageQueryResult<LogiInfo>> QueryPage(DocFilterParameter queryPara)
        {
            var list = await DB.FSql.Select<LogiInfo>()
                .Where(a => a.isdel == false)
                .WhereIf(!string.IsNullOrEmpty(_logiAcct), a => a.LogiAcct.Contains(_logiAcct))
                .WhereIf(!string.IsNullOrEmpty(_logistics_name), a => a.logistics_name.Contains(_logistics_name))
                .WhereIf(!string.IsNullOrEmpty(_logiCompany), a => a.LogiCompany.Contains(_logiCompany))
                .Page(queryPara.PageNo, queryPara.PageSize)
                //.OrderByDescending(a => a.shopGroup)
                .Count(out var c)
                .ToListAsync();

            return new PageQueryResult<LogiInfo>(true, null, list, c);
        }



        public async Task<Result> SaveItem(LogiInfo item)
        {
            if (item == null)
            {
                return new Result(false, "系统错误");
            }

            string err = string.Empty;
            if (string.IsNullOrEmpty(item.logistics_name))
            {
                err += "物流公司名称不能为空!";
            }

            if (string.IsNullOrEmpty(err) == false)
            {
                return new Result(false, err);
            }

            item.isdel = false;
            item.FTime = await DB.FSql.GetTimeAsync();

            if (item.id <= 0)
            {
                var id = await DB.FSql.Insert(item)
                    .ExecuteIdentityAsync();

                item.id = (int)id;
            }
            else
            {
                await DB.FSql.Update<LogiInfo>()
                    .SetSource(item)
                    .ExecuteAffrowsAsync();
            }

            return new Result(true);
        }


        public async Task<Result> SaveItem(IEnumerable<LogiInfo> items)
        {
            if (items == null)
            {
                return new Result(false, "系统错误");
            }

            var time = await DB.FSql.GetTimeAsync();

            foreach (var item in items)
            {
                item.isdel = false;
                item.FTime = time;
                item.IsAgent = item.logistics_name.Contains("代发");
            }

            await DB.FSql.Insert(items).ExecuteAffrowsAsync();

            return new Result(true);

        }




        public async Task<IEnumerable<LogiInfo>> Query(string find)
        {
            var list = await DB.FSql.Select<LogiInfo>()
                .Where(a => a.isdel == false)
                .WhereIf(!string.IsNullOrEmpty(find), a => a.logistics_name.Contains(find) || a.LogiAcct.Contains(find))
                .ToListAsync();

            return list;
        }


        public async Task<IEnumerable<LogiInfo>> QueryLaoban(string find)
        {
            var list = await DB.FSql.Select<LogiInfo>()
                .Where(a => a.isdel == false)
                .WhereIf(!string.IsNullOrEmpty(find), a => a.logistics_name.Contains(find) || a.LogiAcct.Contains(find))
                .Distinct()
                .ToListAsync(a=> new LogiInfo() { LogiAcct = a.LogiAcct });

            return list;
        }


        public async Task<Result<object>> Save(LogiInfo info)
        {
            if (info == null)
            {
                return new Result<object>(false, "系统错误");
            }

            string err = string.Empty;

            if(string.IsNullOrEmpty(info.LogiAcct))
            {
                err = "快递账户不过为空";
            }
            else if (string.IsNullOrEmpty(info.logistics_name))
            {
                err = "模板不过为空";
            }


            if (!string.IsNullOrEmpty(err))
            {
                return new Result<object>(false, err);
            }

            var bl = await DB.FSql.Select<LogiInfo>().
                Where(a => a.isdel == false && a.LogiAcct == info.LogiAcct
                       && a.id != info.id)
                   .AnyAsync();

            if (bl)
            {
                return new Result<object>(false, "快递账户重复,不能使用!");
            }


            if (info.id<=0 )
            {
                var id = await DB.FSql.Insert(info).ExecuteIdentityAsync();

                info.id = (int)id;
            }
            else
            {
                info.isdel = false;

                await DB.FSql.Update<LogiInfo>()
                    .SetSource(info)
                    .ExecuteAffrowsAsync();

            }
            return new Result<object>(true, info.id.ToString(), info.id);
        }

        //public async Task<LogiInfo> GetItem(int id)
        //{
        //    if (id <=0)
        //    {
        //        return null;
        //    }

        //    return await DB.FSql.Select<LogiInfo>()
        //        .Where(a => a.isdel == false && a.id == id)
        //        .ToOneAsync();
        //}

        public async Task<Result<object>> Delete(int id )
        {
            await DB.FSql.Update<LogiInfo>()
               .Where(a=> a.id== id)
               .Set(a=> a.isdel, true)
               .ExecuteAffrowsAsync();

            return new Result<object>(true);
        }

        /// <summary> 同步到服务器 </summary>
        public async Task SyncTo(List<LogiInfo> list)
        {
            var ids = list.Select(a => a.logistics_id).ToArray();
            var old = await DB.FSql.Select<LogiInfo>()
                .Where(a => a.isdel == false && ids.Contains(a.logistics_id))
                .ToListAsync();

            var time = await DB.FSql.GetTimeAsync();

            var updateList = new List<LogiInfo>();
            foreach (var item in old)
            {
                var find = list.FirstOrDefault(a => a.logistics_id == item.logistics_id || a.logistics_name == item.logistics_name);
                if (find != null)
                {
                    find.id = item.id;
                    find.FTime = time;

                    updateList.Add(find);
                }
            }

            await DB.FSql.Update<LogiInfo>()
                .SetSource(updateList)
                .IgnoreColumns(nameof(LogiInfo.IsAgent), nameof(LogiInfo.ItemId), nameof(LogiInfo.Remarks), nameof(LogiInfo.LogiAcct))
                .ExecuteAffrowsAsync();

            //剩下的insert
            var newList = list.Where(a => updateList.Any(c => c.logistics_id == a.logistics_id) == false)
                .ToList();
            foreach (var item in list)
            {
                item.FTime = time;
            }

            await DB.FSql.Insert(newList)
                .ExecuteAffrowsAsync();


        }


        public async Task ModifyLogiInfoName(int id, string name)
        {
            await DB.FSql.Update<LogiInfo>()
                .Where(a => a.id == id)
                .Set(a => a.LogiAcct, name)
                .ExecuteAffrowsAsync();
        }

        public void FireFormShown(object form)
        {
        }

        public void FireFormClosed(object form)
        {
        }

        public async Task<bool> OnBeginEditCell(Func<PageGridCellEditArg> getArgs)
        {
            return await Task.FromResult(false);
        }



        //public async Task<Result> ImportData(IEnumerable<LogiInfo> data)
        //{ 
        //    if(data?.Any() != true)
        //    {
        //        return new Result(false, "没有数据");
        //    }


        //    var time = await DB.FSql.GetTimeAsync();
        //    var batch = Guid.NewGuid().ToString("N");


        //    foreach (var item in data)
        //    {
        //        item.isdel = true;
        //        item.IsAgent = item.logistics_name.Contains("代发");
        //        item.FTime = time;
        //        item.batch = batch;
        //    }

        //    await DB.FSql.Insert(data)
        //        .ExecuteAffrowsAsync();

        //    //删除原先的



        //    return new Result(true);
        //}


    }
}
